package com.huluobo.lc.a1803aretrofitrxdemo.network;

import com.huluobo.lc.a1803aretrofitrxdemo.network.request.Request;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author Lc
 * @description: 网络请求管理类, 用于Retrofit单例
 * @date :2020/11/10 14:10
 */
public class NetWorkManager {
    private static NetWorkManager mInstance;
    private static Retrofit retrofit;
    private static volatile Request request = null;

    //解决了同步的问题的饿汉单例模式
    public static NetWorkManager getInstance() {
        if (mInstance == null) {
            synchronized (NetWorkManager.class) {
                if (mInstance == null) {
                    mInstance = new NetWorkManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 初始化必要的对象和参数
     */
    public void init() {
        //初始化Okhttp
//        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor();
//        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        OkHttpClient client = new OkHttpClient.Builder().build();

        //初始化Retrofit
        retrofit =
                new Retrofit.Builder().client(client).baseUrl(Request.HOST).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();
    }

    public static Request getRequest() {
        if (request == null) {
            synchronized (Request.class) {
                request = retrofit.create(Request.class);
            }
        }
        return request;
    }
}
